#include "GregVoxelizerAdapter.h"
#include "polylib.h"
#include "StaticMesh.h"

GregVoxelizerAdapter::GregVoxelizerAdapter() : mPolyVerts(NULL), mPolys(NULL), mNumVerts(0), mNumPolys(0)
{

}

GregVoxelizerAdapter::~GregVoxelizerAdapter()
{
	if (mPolyVerts)
	{
		for (int i = 0; i < mNumVerts; ++i)
		{
			delete mPolyVerts[i];
		}
		delete[] mPolyVerts;
	}
	if (mPolys)
	{
		for (int i = 0; i < mNumPolys; ++i)
		{
			delete mPolys[i];
		}
		delete[] mPolys;
	}
}

void GregVoxelizerAdapter::Voxelize(DecoRenderData* renderData, const Box& scnBox, BYTE*** solidElements, INT xSize, INT ySize, INT zSize)
{

	convertFromRenderDataToPoly(renderData);
	gtSimulator gtSim;
	gtSim.gtInitialize();
	GregVoxelizer vox(&gtSim);
	vox.SetGeomtryInfo(mPolyVerts, mNumVerts, mPolys, mNumPolys);
	vox.SetParamsAndOutput(xSize, ySize, zSize, scnBox.GetMin().x, scnBox.GetMin().y, scnBox.GetMin().z, scnBox.GetMax().x, scnBox.GetMax().y, scnBox.GetMax().z, solidElements);
	vox.gtRenderScene("vol", 3);

}

void GregVoxelizerAdapter::convertFromRenderDataToPoly(DecoRenderData* renderData)
{
	std::vector<vector3> allVertices;
	renderData->RetrieveAllVertices(allVertices);
	mNumVerts = static_cast<int>(allVertices.size());
	mNumPolys = static_cast<int>(allVertices.size() / 3);

	mPolyVerts = new gtVertex*[mNumVerts];
	mPolys = new gtPolygon*[mNumPolys];

	for (int i = 0; i < mNumVerts; ++i)
	{
		mPolyVerts[i] = new gtVertex;
		mPolyVerts[i]->x = mPolyVerts[i]->ex = allVertices[i].x;
		mPolyVerts[i]->y = mPolyVerts[i]->ey = allVertices[i].y;
		mPolyVerts[i]->z = mPolyVerts[i]->ez = allVertices[i].z;
	}

	for (int i = 0; i < mNumPolys; ++i)
	{
		mPolys[i] = new gtPolygon;
		mPolys[i]->verts = &(mPolyVerts[i * 3]);
		mPolys[i]->num_verts = 3;
		mPolys[i]->id = i;
	}
}
